/*
场景控制，模拟客户端

*/

layui.define(['form','cosjs','scene','storage'], function (exports) {
    let $ = layui.jquery,form = layui.form,cosjs = layui.cosjs,scene = layui.scene;

    function login(data) {
        console.log("hello  this is data-------1:%v",data)
        if(!data['remote']){
            return Promise.reject('remote empty')
        }
        else if(!data['opensdk'] || Object.keys(data['opensdk']).length === 0){
            return Promise.reject('opensdk empty')
        }
        else {
            return data;
        }
    }




    login.finish = function finish(data){
        console.log("hello  this is data-------2:%v",data)
        form.on('submit(gzone-login-submit)', function(){
            let field = arguments[0]['field'];
            let opensdk = field.opensdk;
            if (!opensdk) {
                return scene.error("opensdk empty");
            }
            let opts = {"url":data.remote,'branch':layui.branch,'opensdk':opensdk}
            console.log("hello  this is opts:%v",opts)
            scene.gamesdk = gsdk(opts, cosjs.ajax);        //初始化游戏控制器
            let _curUser=layui.storage('curUser');
            _curUser.set('opts',opts);
            login.verify(field);
            return false;
        })
    }


    login.verify = function verify(data){
        console.log("hello  this is data-------3:%v",data)
        let _curUser=layui.storage('curUser');
        _curUser.set('zoneLoginData',data);
        scene.gamesdk.gzone.login(data).then(ret => {
            let task = scene.gamesdk.gzone.initialize();
            task.on("begin", (k) => {
                let opt = scene.gamesdk.gzone.modules[k];
                console.log(`gzone initialize ${opt.name} begin`);
            })
            task.on("result", (k, err, ret) => {
                let opt = scene.gamesdk.gzone.modules[k];
                console.log(`gzone initialize ${opt.name} finish`, err, ret);
            })
            return task.start();
        }).then(() => {
            scene.show('gzone/select');
        }).catch(err => {
            return cosjs.alert(err);
        })
    }

    exports('gzone/login', login);
})